package com.nk.web.realm;

import com.nk.domain.Employee;
import com.nk.service.EmployeeService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class EmployeeRealm extends AuthorizingRealm {

    @Autowired
    private EmployeeService employeeService;

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        // 获取用户名
        String username = (String) token.getPrincipal();
        // 从数据库查询用户名


        Employee employee = employeeService.getEmployeeByName(username);
        System.out.println("++++++++++++++++++++++:"+employee);
        if (employee == null){
            return null;
        }

        // 认证参数(主体身份，密码，盐，realm的名字)
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee, employee.getPassword(), ByteSource.Util.bytes(employee.getUsername()), this.getName());
        return info;
    }

    // 授权
    @Override
    protected AuthorizationInfo
    doGetAuthorizationInfo(PrincipalCollection principals) {
       // 获取用户主体
        Employee employee = (Employee) principals.getPrimaryPrincipal();
        // 声明权限集合
        List<String> permissionList = null;
        // 声明角色集合
        List<String> roleList = null;
        // 如果是管理员不用查询
        if (employee.getAdmin()){
            permissionList = new ArrayList<>();
            roleList = new ArrayList<>();
            permissionList.add("*:*");
        }else {
            // 查询该员工下所有角色名称
            roleList = employeeService.getRoleNameByEid(employee.getId());
            // 查询该员工拥有的权限
            permissionList = employeeService.getPermissionByEid(employee.getId());
        }

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(roleList);
        authorizationInfo.addStringPermissions(permissionList);
        return authorizationInfo;
    }



}
